package com.conf4j.kit;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.slf4j.LoggerFactory;

import com.conf4j.Conf;
import com.conf4j.ConfigManager;
import com.conf4j.Prop;
import com.conf4j.annotation.Config;

/**
 * 配置工具类
 * 
 * @author dingnate
 *
 */
public final class ConfKit {
	public static final String CONF4J_PROPERTIES = "conf4j.properties";
	public static final String CONF4J_CONFIG_SCANER_LOCAL_PATH = "conf4j.config.scaner.localPath";
	private static String configLocalPath;
	static {
		//-D参数或"conf4j.properties"中conf4j.config.scaner.localPath=config/local/path，
		//config/local/path中的配置文件覆盖类路径中对应的配置文件
		configLocalPath = System.getProperty(ConfKit.CONF4J_CONFIG_SCANER_LOCAL_PATH);
		if (StrKit.isBlank(configLocalPath)) {
			try {
				Prop prop = new Prop(ConfKit.CONF4J_PROPERTIES);
				configLocalPath = prop.get(ConfKit.CONF4J_CONFIG_SCANER_LOCAL_PATH);
			} catch (Exception e) {
				//do nothing
			}
		}
		if (StrKit.isNotBlank(configLocalPath)) {
			try {
				if (configLocalPath.startsWith("~/"))
					configLocalPath = System.getProperty("user.home") + configLocalPath.substring(1);
				configLocalPath = new File(configLocalPath).getCanonicalPath();
			} catch (IOException e) {
				//do nothing
			}
		}
		LoggerFactory.getLogger(ClassLoaderKit.class).error("conf4j.config.scaner.localPath=" + configLocalPath);
	}

	public static void handler(Class<?> clazz) throws Exception, SecurityException {
		// 校验annotation
		Config annotation = clazz.getAnnotation(Config.class);
		if (annotation == null){
			return;
		}
		// 获取单例
		Field meField = clazz.getDeclaredField(Conf.SINGLETON_NAME);
		meField.setAccessible(true);
		Object meObj = meField.get(null);
		if (meObj == null) {
			meObj = clazz.newInstance();
			meField.set(null, meObj);
		}
		// 注册
		ConfigManager.addConfig(meObj);
		// 属性注入
		String file = annotation.file();
		if (StrKit.isBlank(file)){
			return;
		}
		Prop prop = new Prop(file);
		ConfigManager.putProperties(prop.getProperties());
		String prefix = annotation.prefix();
		for (Method method : ConfigManager.getClassSetMethods(clazz)) {
			String value = prop.get(ConfigManager.getKeyByMethod(prefix, method));
			if (StrKit.isNotBlank(value)) {
				Object val = ValueKit.convert(value, method.getParameterTypes()[0]);
				method.invoke(meObj, val);
			}
		}
	}

	/**
	 * 获取文件版本
	 * 
	 * @param file
	 * @return
	 */
	public static String getVersion(File file) {
		return "time:" + file.lastModified();
	}

	/**
	 * @return the scanerLocalPath
	 */
	public static final String getConfigLocalPath() {
		return configLocalPath;
	}
}
